<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="模板地址" prop="templateUrl">
                <el-input v-model="queryParams.templateUrl" placeholder="请输入模板地址" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
      <!-- <el-form-item label="逻辑删除;0=未删除；1=已删除" prop="isDelete">
                <el-input v-model="queryParams.isDelete" placeholder="请输入逻辑删除;0=未删除；1=已删除" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:template:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:template:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:template:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:template:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="templateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="颜色属性ID" align="center" prop="id" /> -->
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="模板地址" align="center" prop="templateUrlFull">
        <template slot-scope="scope">
          <el-button size="mini" @click="downLoadFile(scope.row.templateUrl)">
            下载
          </el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:template:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:template:remove']">删除</el-button> -->
        </template>
      </el-table-column>
      <el-table-column
        label="模板类型;导入类型=import"
        align="center"
        prop="templateType"
      />
      <!-- <el-table-column label="逻辑删除;0=未删除；1=已删除" align="center" prop="isDelete" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:template:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:template:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色模板数据字典定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="选择文件" prop="templateUrl">
          <!-- list-type="picture-card" label-width="40"-->
          <el-upload
            :action="imgUpload.url"
            :headers="imgUpload.headers"
            :limit="limit"
            :on-exceed="handleExceed"
            :on-success="handlePictureSuccessPic"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :file-list="fileLi"
          >
            <el-button size="small" type="primary">选择文件</el-button>
            <!-- <i class="el-icon-plus"></i> -->
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <div width="50%" v-if="fileLi">文件已上传</div>
            <!-- :src="imageUrl" -->
          </el-dialog>
        </el-form-item>
        <!-- <el-form-item label="模板地址" prop="templateUrl">
                    <el-input v-model="form.templateUrl" placeholder="请输入模板地址" />
                </el-form-item> -->
        <!-- <el-form-item label="逻辑删除;0=未删除；1=已删除" prop="isDelete">
                    <el-input v-model="form.isDelete" placeholder="请输入逻辑删除;0=未删除；1=已删除" />
                </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
} from "@/api/data/template";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  name: "Template",
  data() {
    return {
      dialogVisible: false,
      // 图片数量限制
      limit: 1,
      file: "",
      fileLi: [{ url: "" }],
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      pjtUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色模板数据字典定义表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        templateName: null,
        templateUrl: null,
        templateType: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    downLoadFile(value) {
      console.log(JSON.stringify(value));
      window.location.href = this.pjtUrl + value;

      // download.resource(value)
      //根据文件路径参数，按斜杠进行分割，取得文件名，这是download函数需要的第三个参数
      let list = value.split("/");
      let fileName = list[list.length - 1];
      //这是文件路径参数，因为download函数需要传三个参数，这是第二个参数
      let params = {
        resource: value,
      };
      /** request里面的download下载函数 */
      //download函数是若依自带的，第一个参数是请求的url路径，不需要变，这个路径下的controller后台方法也是若依写好封装好了的。
      // download("/common/download/resource", params, fileName);
      // console.log("文件名");
      // console.log("value");
    },
    /** 查询角色模板数据字典定义列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then((response) => {
        this.templateList = response.rows;
        console.log(JSON.stringify(this.templateList));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roleName: null,
        templateName: null,
        templateUrl: null,
        templateType: null,
        isDelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色模板数据字典定义";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTemplate(id).then((response) => {
        this.file = response.data.templateUrl;
        this.fileLi = [
          { url: process.env.VUE_APP_BASE_API + response.data.templateUrl },
        ]; //logo图片加的是这一行
        this.form = response.data;
        this.open = true;
        this.title = "修改角色模板数据字典定义";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.templateUrl = this.file;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          '是否确认删除角色模板数据字典定义编号为"' + ids + '"的数据项？'
        )
        .then(function () {
          return delTemplate(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/template/export",
        {
          ...this.queryParams,
        },
        `template_${new Date().getTime()}.xlsx`
      );
    },
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 5MB!");
      }
      return isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.picUrl = file.url;
      this.imageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureSuccessPic(res, file) {
      //设置图片访问路径 （url 后台传过来的的上传地址）
      // this.picUrl = file.response.url;
      // // const url = file.response.fileName;
      // this.picurl = file.response.urle;
      this.file = file.response.fileName;
      console.log(this.file);
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
    },
  },
};
</script>
  